package com.soft.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Date;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FileDownloadHelper
{

	private static final Logger log = LoggerFactory.getLogger(FileDownloadHelper.class);

	public FileDownloadHelper()
	{
	}

	public static void main(String args[])
	{
		String dataDir = "d:\\data";
		String poster1 = "http://img1.mtime.com/mt/929/94929/94929.jpg";
		String p2 = "http://img1.mtime.com/mt/47/10047/10047.jpg";
		FileDownloadHelper.download(dataDir, poster1);
		FileDownloadHelper.download(dataDir, p2);
	}

	public static void download(String dataDir, String poster)
	{
		BufferedInputStream in;
		BufferedOutputStream out;
		File file;
		File tempfile;
		in = null;
		out = null;
		String distPath = FileDownloadHelper.getDownloadFileDist(dataDir, poster);
		file = new File(distPath);
		if (file.exists())
		{
			log.warn("文件{}已存在", file.getAbsoluteFile());
			return;
		}
		tempfile = null;
		try {
			tempfile = File.createTempFile("jpg", ".tmp");
			out = new BufferedOutputStream(new FileOutputStream(tempfile));
			java.net.URL url = new URL(poster);
			java.net.URLConnection conn = url.openConnection();
			conn.addRequestProperty("Accept-Language", "zh-cn");
			conn.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7 GTB5");
			conn.setReadTimeout(60000);
			int length = conn.getContentLength();
			log.info("从{}得到文件长度{}", url, Integer.valueOf(length));
			in = new BufferedInputStream(conn.getInputStream());
			byte buf[] = new byte[4096];
			int bytesRead = 0;
			java.util.Date sd = new Date();
			int count = 0;
			do
			{
				if (bytesRead < 0)
					break;
				out.write(buf, 0, bytesRead);
				bytesRead = in.read(buf);
				count += bytesRead;
			} while ((new Date()).getTime() - sd.getTime() <= 60000L || count >= 60000);
			log.info("{},下载速度小于1K,放弃");
			out.flush();
			
			if (tempfile != null)
				tempfile.delete();
			log.info("下载{}异常!", poster);			
			FileDownloadHelper.move(tempfile, file);
			
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally{
			if (out != null)
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			if (in != null)
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
		
		
		
	}

	private static boolean move(File srcFile, File destFile)
	{
		try
		{
			FileUtils.copyFile(srcFile, destFile);
			srcFile.delete();
		}
		catch (IOException e)
		{
			e.printStackTrace();
			log.error("{}", e);
			return false;
		}
		return true;
	}

	public static String getDownloadFileDist(String dataDir, String url)
	{
		if (StringUtils.isBlank(url) || StringUtils.isBlank(dataDir))
			throw new IllegalArgumentException("空参数");
		if (!dataDir.endsWith(File.separator))
			dataDir = (new StringBuilder()).append(dataDir).append(File.separator).toString();
		String result = url.replace("http://img1.mtime.com/", dataDir).replace('/', File.separatorChar).replace('\\', File.separatorChar);
		log.info("下载目标地址:{}", result);
		return result;
	}

	public static String getPosterUrl(String poster)
	{
		if (StringUtils.isNotBlank(poster))
			poster = poster.replaceAll("http://img1.mtime.com", "");
		return poster;
	}

}
